from foaflib import FoafGraph
import rdflib

from foaflib import foaf_uriref

_SINGLETONS = """accountServiceHomepage accountName accountProfilePage""".split()
_BASIC_MULTIS = """""".split()

class OnlineAccount(object):

    def __init__(self, graph=None, node=None):
        for name in _BASIC_MULTIS:
            setattr(self, "_get_%ss" % name, self._make_getter(name))
            setattr(Agent, "%ss" % name, property(self._make_property_getter(name)))
            setattr(self, "add_%s" % name, self._make_adder(name))
            setattr(self, "del_%s" % name, self._make_deler(name))

        self._graph = FoafGraph()

        if graph and node:
            self._me = node

            for name in _SINGLETONS:
                for value in graph.objects(subject=self._me, predicate=foaf_uriref(name)):
                    self._graph.add((self._me, foaf_uriref(name), value))


    ''' For the _SINGLETONS '''
    def __getattr__(self, name):
        if name in _SINGLETONS:
            for raw in self._graph.objects(subject=self._me, predicate=foaf_uriref(name)):
                return str(raw)
            return None
        raise AttributeError(name)

    def __setattr__(self, name, value):
        if name in _SINGLETONS:
            self._graph.remove((self._me, foaf_uriref(name), None))
            self._graph.add((self._me, foaf_uriref(name), value))
        else:
            super().__setattr__(name, value)

    ''' For the _BASIC_MULTIS '''
    def _make_getter(self, name):
        def method():
            return [str(x) for x in self._graph.objects(subject=self._me, predicate=foaf_uriref(name))]
        return method

    def _make_property_getter(self, name):
        def method(self):
            return [str(x) for x in self._graph.objects(subject=self._me, predicate=foaf_uriref(name))]
        return method

    def _make_adder(self, name):
        def method(value):
            self._graph.add((self._me, foaf_uriref(name), rdflib.URIRef(value)))
        return method

    def _make_deler(self, name):
        def method(value):
            self._graph.remove((self._me, foaf_uriref(name), rdflib.URIRef(value)))
        return method
